package binbase.web

import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap

/**
 * Created by IntelliJ IDEA.
 * User: wohlgemuth
 * Date: 8/25/11
 * Time: 4:37 PM
 * To change this template use File | Settings | File Templates.
 */
class QueryUtil {

    /**
     * builds the actual query in the system
     * @param params
     * @param query
     * @return
     */
    public static def buildQuery(GrailsParameterMap params, StringBuffer query, def propertiesToRender) {
        def sortDir = params.sSortDir_0?.equalsIgnoreCase('asc') ? 'asc' : 'desc'

        def sortProperty = 0

        if (params.iSortCol_0) {
            sortProperty = Integer.parseInt(params.iSortCol_0.toString())
        }

        query.append(" order by ${propertiesToRender[sortProperty]} ${sortDir}")

        if ((params.iDisplayLength as int) > 0) {
            if (params.iDisplayLength) {

                query.append(" LIMIT ${Integer.parseInt(params.iDisplayLength.toString())}")
            }

            if (params.iDisplayStart) {
                query.append(" OFFSET ${Integer.parseInt(params.iDisplayStart.toString())}")
            }
        }
    }
}
